# -*- coding: utf-8 -*-
from qsiauth.myuser import myauthorise
import webapp2
from webapp2_extras import jinja2
from qsiauth import models
from qsiauth import constants
from google.appengine.ext import ndb


class Jinja2Handler(webapp2.RequestHandler):
    """
        BaseHandler for all requests all other handlers will
        extend this handler

    """
    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    @webapp2.cached_property
    def user_session(self):
        """Shortcut to access the session.
        :returns
          A dictionary of the current session from the models.Session with or
          without the user being logged in
        """
        return self.request.session if self.request.session else None

    @webapp2.cached_property
    def user_info(self):
        """Shortcut to access a subset of the user attributes that are stored
        as per the session.
        :returns
          A dictionary with user information from models.User
        """
        return self.request.user if self.request.user else None

    @webapp2.cached_property
    def user_profile(self):
        """Shortcut to access a subset of the user profiles as per the user_info()
        :returns
          A dictionary with user information from models.UserProfile
        """
        profiles = None
        if self.user_info:
            profile_keys = [ndb.Key('UserProfile', p) for p in self.user_info.auth_ids]
            profiles = ndb.get_multi(profile_keys)
        return profiles

    def get_messages(self, key='_messages'):
        try:
            return self.request.session.data.pop(key)
        except KeyError:
            return None

    def render_template(self, template_name, template_values={}):
        messages = self.get_messages()
        template_values.update({'title': constants.TITLE,'alt': constants.TITLE})
        if messages:
            template_values.update({'messages': messages})
        self.response.write(self.jinja2.render_template(
            template_name, **template_values))

    def render_string(self, template_string, template_values={}):
        self.response.write(self.jinja2.environment.from_string(
            template_string).render(**template_values))

    def json_response(self, json):
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(json)

#import the user level decorators
from qsiauth.myuser import *


class PageHandler(Jinja2Handler):

    def root(self):
        self.render_template('login.html', {
            'user': self.user_info,
            'session': self.user_session,
            'profiles': self.user_profile,
        })

class ExternalAccounts(Jinja2Handler):
    """Dirty way of hiding url and checking whether a user exists before redirecting
    to the actual external providers /auth
    """
    def get(self):
        if self.user_info:
            self.redirect("/",abort=True)
        loc = None
        provider = self.request.get('provider')
        if provider == "google":
            loc = "/auth/google"
        if provider == "linkedin":
            loc = "/auth/linkedin"
        else:
            loc = "/auth/appengine_openid?provider=" + provider
        self.redirect(loc,abort=True)

class TestPage(Jinja2Handler):
    """purely for testing pages accessibility"""
    @myauthorise('user')
    def get(self):
        self.response.write('IN')

def wipe_datastore():
    users = models.User.query().fetch()
    profiles = models.UserProfile.query().fetch()
    tokens = models.UserToken.query().fetch()
    sessions = models.Session.query().fetch()

    for t in [users, profiles, tokens, sessions]:
        for i in t:
            i.key.delete()

class WipeDSHandler(webapp2.RequestHandler):

    def get(self):
        # TODO: discover why importing deferred outside of a
        # function causes problems with jinja2 filters.
        from google.appengine.ext import deferred
        deferred.defer(wipe_datastore)